<template>
	<el-tabs v-model="editableTabsValue" type="card" editable @edit="handleTabsEdit">
		<el-tab-pane :key="item.name" v-for="(item, index) in tabList"  :label="item.title" :name="item.name">
		</el-tab-pane>
	</el-tabs>
</template>
<script>
	import { mapMutations, mapGetters } from 'vuex'
	import { DEFAUL_INDEX } from '@/utils/config.js'
	export default {
		props: {
			targetList: {
				required: false,
				type: [Array, Object],
			}
		},
		data() {
			return {
				editableTabsValue: '1',
				tabIndex: 1,
				tabName: '',
				setFlag: false
			}
		},
		methods: {
			/**
			 * @author yang
			 * @desc 处理添加或删除tab的交互
			 * @param {targetName} 当前name 值
			 * @param {action} 'remove' || 'add'
			 */
			handleTabsEdit(targetName, action) {
				if(action === 'remove' && targetName && this.tabList.length > DEFAUL_INDEX ) {
					this.setFlag = true
					let list = this.tabList
					let activeName = this.editableTabsValue
					list.forEach((item, index) => {
						if(item.name == targetName) {
							let nextTab = list[index + DEFAUL_INDEX] || list[index - DEFAUL_INDEX]
							list.splice(index, DEFAUL_INDEX)
							if(nextTab) {
								activeName = nextTab.name
							}
						}
					})
					this.editableTabsValue = activeName
					this.setTabCurrentIndex(parseInt(this.editableTabsValue))
					this.setTabList(list.filter(tab => list.name !== targetName))
					setTimeout(() => {
						this.setFlag = false
					}, 200)
				}
			},
			...mapMutations({
				setTabList: 'SET_TAB_LIST',
				setTabCurrentIndex: 'SET_TAB_CURRENT_INDEX'
			}),
		},
		computed: {
			...mapGetters([
				'tabList',
				'tabCurrentIndex'
			])
		},
		watch: {
			editableTabsValue(val){
				console.log(val)	
				this.setTabCurrentIndex(parseInt(val))
			},
			tabList(val, oldValue) {
				if(!this.setFlag ) {
					console.log(val)
					console.log(this.tabCurrentIndex)
					val.forEach((item) => {
						if(item.name ==  this.tabCurrentIndex){
							this.editableTabsValue = item.name
						}
					})
					
				}
			},
			targetList: {
				handler: function(val,oldval){
					console.log(val)
					let attr = this.tabList.filter((item) => {return item.title == val.title})
					console.log(attr)
					console.log(333)
					if(val && val.name && !attr.length){
						let list = this.tabList
						list.push(val)
						this.setTabList(list)
						
					}
					this.editableTabsValue = val.name
				},
				deep:true
			},
			tabCurrentIndex(val){
				this.tabList.forEach((item) => {
					if(item.name ==  val){
						this.editableTabsValue = item.name
					}
				})
			}
			
		},
		
	}
</script>